<?php
namespace Action;
use HY\Action;
!defined('HY_PATH') && exit('HY_PATH not defined.');
class Task extends HYBBS {

    //类中使用的路径
    /**
     * 20230813
     * 主要的任务控制都在这里边
     * 文件收发部分在task2里边
     * 20230813
     * 增加加速网关部分功能
    */

	public function __construct() {
		parent::__construct();
		//{hook a_post_init}
		if(!IS_LOGIN){
			if(IS_AJAX && IS_POST){
				die($this->json(array('error'=>false,'info'=>'请登录后再操作')));
			}
			else{
				header("location: ". HYBBS_URLA('user','login'));
				die;
			}

		}
	}

	public function Rview(){
		//打开接收任务界面
        //win程序遗留 后续考虑删除
		$task = S('fhl_ctask')->query('select * from hy_fhl_stask')->fetchALL();
		$this->v('task',$task);
		$this->view = 'FHL';
		$this->display('Rtask');

	}
	public function Tview(){
		//打开发送任务界面
        //win程序遗留 后续考虑删除
		$task = S('fhl_ctask')->query('')->fetchALL();
		$this->v('task',$task);
		$this->view = 'FHL';
		$this->display('Ttask');

	}
    public function Pview(){
        //打开发送任务界面 socket代理
        //$task = S('fhl_ctask')->query('')->fetchALL();
        //$this->v('task',$task);
        $this->view = 'FHL';
        $this->display('Ptask');

    }
    //打开网关加速页面 tun技术
    public function Gview(){
        //打开发送任务界面
        $pList = M("Sysinfo")->execCmd(' ps -elf |grep \'sudo /home/wwwroot/FHL/FSTCP\' |awk -F \'root/FHL/\' \'{print $2}\'');
        $pList = explode("\n",trim($pList));
        //关掉进程
        $hasRun = false;
        $cmd = '';
        $isDirectRoute = false;
        $directRoute = '';
        foreach($pList as $k=>$v){
            $vArry = explode(" ",$v);
            //$this->json("proxy".$task['type']);
            if(strpos($v,"-p")){
                $hasRun = true;
                $cmd = $v;
            }
        }
        $Gtask = S('fhl_gtask')->query('select * from hy_fhl_gtask WHERE  gid = 1')->fetchALL()[0];
        //判断直通路由是否存在
        if(!$hasRun){

            $pList = M("Sysinfo")->execCmd('/usr/sbin/route -n');
            $pList = explode("\n",trim($pList));
            foreach($pList as $k=>$v){

                //$this->json("proxy".$task['type']);
                if(strpos($v,$Gtask['destination'])!== false){
                    $isDirectRoute = true;
                    $directRoute = $v;

                }
            }
        }

        $this->v('Gtask',$Gtask);
        $this->v('hasRun',$hasRun);
        $this->v('cmd',$cmd);
        $this->v('isDirectRoute',$isDirectRoute);
        $this->v('directRoute',$directRoute);
        $this->view = 'FHL';
        $this->display('Gtask');

    }

    //打开TCP网关加速页面
    //目录下有一个接收端
    //10个发送端 需要从目录下遍历信息 然后反馈到前台
    public function TCPGview(){
        //打开发送任务界面
        $pList = M("Sysinfo")->execCmd('ps -elf |grep \'FTCPG\'|grep -v \' www \'|grep \'sudo\'');
        $pList = explode("\n",trim($pList));
        //关掉进程
       
        $state = ['Remote'=>false];
        for($j=1;$j<=10;$j++){
             $state['Local'.$j]=false;   
        }

       //判断运行状态
        foreach($pList as $k=>$v){
            $vArry = explode("FTCPG_",$v);
            if(count($vArry)>1){
                $state[$vArry[1]]=true;
            }
            
        }
        //$this->json($state);
        //遍历文件夹 然后形成进程情况数组
        $Gtask = [];
        for ($i=0; $i<=10; $i++)
        {
            //0是服务端 用于接收任务
            if($i == 0){
                $iniArray =parse_ini_file(INDEX_PATH . 'FHL/tcpGateWay/'.$i.'/remote.ini');
                $iniArray['name']='服务端';
                $iniArray['remoteip']='-';
                $iniArray['remoteport']='-';
                $iniArray['speednet']='-';
                $iniArray['isrun']=$state['Remote'];
            }else{
                $iniArray =parse_ini_file(INDEX_PATH . 'FHL/tcpGateWay/'.$i.'/local.ini');
                $iniArray['name']='客户端';
                $iniArray['localport']=$iniArray['listenport'];
                $iniArray['isrun']=$state['Local'.$i];
            }
            $iniArray['ID']=$i;
            array_push($Gtask,$iniArray);
        }
        //$Gtask = S('fhl_gtask')->query('select * from hy_fhl_gtask WHERE  gid = 2')->fetchALL()[0];
        //判断直通路由是否存在
        //$this->json($Gtask);
        $this->v('Gtask',$Gtask);
       
        
        //$this->v('isDirectRoute',$isDirectRoute);
        //$this->v('directRoute',$directRoute);
        $this->view = 'FHL';
        $this->display('TCPGtask');

    }
/**
 * 2023
 * 增加代理任务信息
 * windows系统遗留 可以删除
*/
    public function getTaskList(){
        $currHost = X('get.currHost');
        $type = X('get.type');
        if($currHost == 'local'){
            if($type == 't'){
                $list = S('fhl_ctask')->query('
                      SELECT taskid,lport,ip,port,t,m,p,ow,SD dir,deep,df,info,run,\'t\' type
                      FROM hy_fhl_ctask where taskid = 0
                      UNION
                      SELECT taskid,port lport,\'本节点IP\' ip,port,\'0\' t,m,\'1\' p,\'-\' ow,TD dir,\'-\' deep,\'-\' df,info,run,\'r\' type
                      FROM hy_fhl_stask where taskid > 0
                                        ')->fetchALL();
                $this->json([
                    'error'=>true,
                    'data'=>$list,
                    'count'=>count($list)
                ]);
            }elseif($type == 'p'){
                $list = S('fhl_ptask')->query('select * from hy_fhl_ptask')->fetchALL();
                $this->json([
                    'error'=>true,
                    'data'=>$list,
                    'count'=>count($list)
                ]);
            }else{
                $list = S('fhl_ctask')->query('
                      SELECT taskid,port lport,\'本节点IP\' ip,port,\'0\' t,m,\'1\' p,\'-\' ow,TD dir,\'-\' deep,\'-\' df,info,run,\'r\' type
                      FROM hy_fhl_stask where taskid = 0
                      UNION
                      SELECT taskid,lport,ip,port,t,m,p,ow,SD dir,deep,df,info,run,\'t\' type
                      FROM hy_fhl_ctask where taskid > 0
                                        ')->fetchALL();

                $this->json([
                    'error'=>true,
                    'data'=>$list,
                    'count'=>count($list)
                ]);

            }

        }
    }
    //编辑代理加速 kcp通道模式
    public function editPTask(){
        $level = intval(X("post.level"));
        $lport = intval(X("post.lport"));
        $rip = trim(X("post.rip"));
        $rport = intval(X("post.rport"));
        $sndwnd = intval(X("post.sndwnd"));
        $rcvwnd = intval(X("post.rcvwnd"));
        $ipspeed = intval(X("post.ipspeed"));
        $hhtimeout = intval(X("post.hhtimeout"));
        $hhbuf = intval(X("post.hhbuf"));
        $mtu = intval(X("post.mtu"));
        $interval = intval(X("post.interval"));
        $timeout = intval(X("post.timeout"));
        $taskid = intval(X("post.taskid"));

        if(!filter_var($rip,FILTER_VALIDATE_IP))
        {
            $this->json([
                'state'=>false,
                'info'=>"rip错误"
            ]);
        }
        S('fhl_ptask')->update([
            "level"=>$level,
            "lport"=>$lport,
            "rip"=>$rip,
            "rport"=>$rport,
            "sndwnd"=>$sndwnd,
            "rcvwnd"=>$rcvwnd,
            "ipspeed"=>$ipspeed,
            "hhtimeout"=>$hhtimeout,
            "hhbuf"=>$hhbuf,
            "mtu"=>$mtu,
            "interval"=>$interval,
            "timeout"=>$timeout,
        ],["taskid"=>$taskid]);

        $this->json([
            'state'=>true,
            'info'=>"已修改"
        ]);

    }
	public function editTask(){
		$taskid = intval(X("post.taskid"));
		$type = X("post.type");
		$info = X("post.info");

        $localport = X("post.localport");
        $remoteip = X("post.remoteip");
        $remoteport = X("post.remoteport");
        $speednet = X("post.speednet");
        $id = X("post.id");

		$m = X("post.mode");
		$port = intval(X("post.port"));
        $lport = $port+1000;
        //$this->json(array('error'=>true,'info'=>'修改成功'));
		if($type == 't'){
			//修改发送任务
			$p = intval(X("post.p"));
			$ip = X("post.ip");
			//如果是主任务 要同时修改接收任务模式
            //如果不是主任务 则不能修改漠视你
            if($taskid == 0){
                S('fhl_ctask')->update([
                    'info'=>$info,
                    'm'=>$m,
                    'ip'=>$ip,
                    'port'=>$port,
                    'lport'=>$lport,
                    'p'=>$p
                ],[
                    'taskid'=>$taskid
                ]);
                S('fhl_stask')->update([
                    'm'=>$m,
                ],[
                    'taskid[>]'=>0
                ]);
            }else{
                S('fhl_ctask')->update([
                    'info'=>$info,
                    'ip'=>$ip,
                    'port'=>$port,
                    'lport'=>$lport,
                    'p'=>$p
                ],[
                    'taskid'=>$taskid
                ]);
            }
			$this->json(array('error'=>true,'info'=>'修改成功'));
		}elseif($type == 'r'){
			//修改接收任务
            if($taskid == 0){
                S('fhl_stask')->update([
                    'info'=>$info,
                    'm'=>$m,
                    'port'=>$port,
                ],[
                    'taskid'=>$taskid
                ]);
                S('fhl_ctask')->update([
                    'm'=>$m,
                ],[
                    'taskid[>]'=>0
                ]);
            }else{
                S('fhl_stask')->update([
                    'info'=>$info,
                    'm'=>$m,
                    'port'=>$port,
                ],[
                    'taskid'=>$taskid
                ]);
            }

			$this->json(array('error'=>true,'info'=>'修改成功'));

		}elseif($type == 'TCPG'){
            //修改tcp加速网关的配置文件
            if($id == 0){
                $ini=['udxcfg'=>[
                  'localport'=>  $localport
                ]];
                $error = M('File')->write_ini_file($ini,INDEX_PATH . 'FHL/tcpGateWay/'.$id.'/remote.ini',true);
            }else{
                $ini=['udxcfg'=>[  
                                    'remoteip'=>  $remoteip,
                                    'remoteport'=>  $remoteport,
                                    'speednet'=>  $speednet,
                                 ],
                        'channelcfg'=>[
                                    'listenport'=>  $localport,
                                ]  
                    ];
                  $error = M('File')->write_ini_file($ini,INDEX_PATH . 'FHL/tcpGateWay/'.$id.'/local.ini',true);
            }
            

            $this->json(array('error'=>$error['error'],'info'=>$error['info']));

        }


}
    public function autoTest(){
        $type = X('get.type');
        if($type == 'g'){ //网关加速
            $localGate = X('get.localGate');
            $remoteGate = X('get.remoteGate');
            $pList = M("Sysinfo")->execCmd(' ps -aux |grep \'sudo /home/wwwroot/FHL/FHLtun\'|grep -v \'sh -c\'|awk \'{print $13" "$14" "$15" "$16" "$17" "$18" "$19" "$20" "$21" "$22" "$23}\'');
            //$pList = M("Sysinfo")->execCmd('ps -elf|grep sudo');
            //$pList=M("Sysinfo")->execCmd(INDEX_PATH."/FHL/FHLcontrol -lic");
            $pList = explode("\n",trim($pList));  
            if(count($pList)!=2){
                $this->json([
                    "state"=>false,
                    "info"=>["程序未启动失败"],
                    "res"=>$pList
                ]);
            }
            $runinfo = explode(" ",trim($pList[0]));
            $res = [];
            if($runinfo[0]=="-s"){
                array_push($res,"当前运行模式为服务端");
                array_push($res,"加速通道占用IP:".$runinfo[2]);
                array_push($res,"对端加速子网IP:".$runinfo[6]);
                array_push($res,"对端加速子网掩码:".$runinfo[8]);
                $resport =M("Sysinfo")->execCmd('sudo /usr/bin/netstat  -nlatup |grep FHLtun|awk \'{print $1" "$4" "$5}\'');
                $resport = explode("\n",trim($resport));
               
                if(count($resport)!=1){
                    array_push($res,"端口".$res[4]."占用异常");
                    $this->json([
                        "state"=>true,
                        "info"=>$res,
                    ]);
                }
                $resport = explode(" ",trim($resport[0]));
                //检测到端口占用后
                array_push($res,"内部端口占用".$resport[0]."协议:".$resport[1]);
                array_push($res,"外部端口占用:".$resport[2]);
                $testip = explode(":",$resport[1])[0];
                $testport = explode(":",$resport[1])[1];
                $resping =M("Sysinfo")->execCmd("/home/wwwroot/FHL/FHLping ".$testip." ".$testport);
                array_push($res,"加速协议连接测试结果".$resping);
                $resping =M("Sysinfo")->ping($remoteGate,$localGate);
                array_push($res,"加速子网连接测试结果".implode('',$resping));
            }else{
                array_push($res,"当前运行模式为客户端");
                array_push($res,"加速通道占用IP:".$runinfo[2]);
                 array_push($res,"远端IP".$runinfo[4]."端口:".$runinfo[6]);
                array_push($res,"对端加速子网IP:".$runinfo[8]);
                array_push($res,"对端加速子网掩码:".$runinfo[10]);
                $resport =M("Sysinfo")->execCmd('sudo /usr/bin/netstat  -nlatup |grep FHLtun|awk \'{print $1" "$4" "$5}\'');
                $resport = explode("\n",trim($resport));
               
                if(count($resport)!=1){
                    array_push($res,"进程异常");
                    $this->json([
                        "state"=>true,
                        "info"=>$res,
                    ]);
                }
                $resport = explode(" ",trim($resport[0]));
                //检测到端口占用后
                array_push($res,"内部端口占用".$resport[0]."协议:".$resport[1]);
                array_push($res,"外部端口占用:".$resport[2]);
                
                $resping =M("Sysinfo")->execCmd("/home/wwwroot/FHL/FHLping ".$runinfo[4]." ".$runinfo[6]);
                array_push($res,"服务端连接测试结果".$resping);
                $resping =M("Sysinfo")->ping($remoteGate,$localGate);
                array_push($res,"加速子网连接测试结果".implode('',$resping));
                
            }
            $this->json([
                "state"=>true,
                "info"=>$res,
            ]);
        }else if($type == 'p'){//代理加速
            $res = [];
            $runState = 'unknow';
            $pList = M("Sysinfo")->execCmd(' ps -aux |grep \'sudo /home/wwwroot/FHL/FHLproxy\'|grep -v \'sh -c\'');
            //$pList = M("Sysinfo")->execCmd('ps -elf|grep sudo');
            //$pList=M("Sysinfo")->execCmd(INDEX_PATH."/FHL/FHLcontrol -lic");
            
            $pList = explode("\n",trim($pList));
          
            if(count($pList)==2){
                $runState = 'server';
                
                array_push($res,"代理服务端已启动");
            }
            $pList = M("Sysinfo")->execCmd(' ps -aux |grep \'sudo /home/wwwroot/FHL/FHLsocket5\'|grep -v \'sh -c\'|awk \'{print $13}\'');
            //$pList = M("Sysinfo")->execCmd('ps -elf|grep sudo');
            //$pList=M("Sysinfo")->execCmd(INDEX_PATH."/FHL/FHLcontrol -lic");
            $pList = explode("\n",trim($pList));
            
            if(count($pList)==2){
                $runState = 'client';
                array_push($res,"代理客户端已启动");
                //测试加速协议联通性
                $resping =M("Sysinfo")->execCmd("/home/wwwroot/FHL/FHLping ".$pList[0]." 2000");
                array_push($res,"服务端".$pList[0]."加速协议连接测试结果".$resping);
                $resping =M("Sysinfo")->ping($pList[0]);
                array_push($res,"服务端".$pList[0]."ping测试结果".implode('',$resping));  

            }
            if($runState == 'unknow'){
                $this->json([
                    "state"=>true,
                    "info"=>['本加速器未启动客户端或服务端'],
                    //"con"=>$cmdtail
                ]);
            }
            $resPort =M("Sysinfo")->execCmd("/usr/bin/netstat  -nlatup |grep 2000");
            $resPort=explode("\n",trim($resPort,"\n"));
            array_push($res,"2000端口占用情况：");  
            array_push($res,$resPort);  
            $this->json([
                "state"=>true,
                "info"=>$res,
                //"con"=>$cmdtail
            ]);
        }else if($type == 'tcp_g'){ //网关加速
            $pList = M("Sysinfo")->execCmd('ps -elf |grep \'FTCPG\'|grep -v \' www \'|grep \'sudo\'');
            $pList = explode("\n",trim($pList));
            //关掉进程
           
            $state = ['Remote'=>false];
            for($j=1;$j<=10;$j++){
                 $state['Local'.$j]=false;   
            }
    
           //形成运行状态矩阵
            foreach($pList as $k=>$v){
                $vArry = explode("FTCPG_",$v);
                if(count($vArry)>1){
                    $state[$vArry[1]]=true;
                }
                
            }
            $res = [];
            for ($i=0; $i<=10; $i++)
            {
                //0是服务端 用于接收任务
                if($i == 0){
                    $iniArray =parse_ini_file(INDEX_PATH . 'FHL/tcpGateWay/'.$i.'/remote.ini'); 
                    $isrun=$state['Remote']?'[运行正常]':'[未运行]';
                    array_push($res,'服务端'.$isrun.'监听udp端口'.$iniArray['localport']);
                }else{
                    $iniArray =parse_ini_file(INDEX_PATH . 'FHL/tcpGateWay/'.$i.'/local.ini');
                    $isrun=$state['Local'.$i]?'[运行正常]':'[未运行]';
                    array_push($res,'客户端['.$i.']'.$isrun.'加速网段'.$iniArray['speednet']);
                    $resping =M("Sysinfo")->execCmd("/home/wwwroot/FHL/FHLping ".$iniArray['remoteip']." ".$iniArray['remoteport']);
                    array_push($res,'客户端['.$i.']到'.$iniArray['remoteip'].':'.$iniArray['remoteport'].'['.$resping.']');
                }
            }
            
            $this->json([
                "state"=>true,
                "info"=>$res,
            ]);

        }else{
            $this->json([
                "state"=>false,
                "info"=>"测试失败",
                //"con"=>$cmdtail
            ]);
        }

    }
	public function restartTask(){
		$type = X('get.type');
		$taskid = intval(X('get.taskid'));
		if($type == 't'){
		    //发送任务
			$task = S('fhl_ctask')->query('select * from hy_fhl_ctask where taskid = '.$taskid)->fetchALL()[0];
			$this->existFHLexe("FastExe_ct".$taskid.'.exe');
			$this->existFHLdir(C('FHLdirroot').$task['SD']);
            exec('taskkill /f /im FastExe_ct'.$taskid.'.exe',$out);
			$cmd ='start /b '.PATH.'FHL/FastExe_ct'.$taskid.'.exe -c '.$task['lport'].' '.$task['ip'].' '.$task['port'].' -t 1 '.'-p '.$task['p'].' -SD '
                .C('FHLdirroot').$task['SD'].' -m '.$task['m'].' -deep 1  -ow 0  -df 1 ';
            $bat = fopen(PATH."FHL/runFastExe_ct".$taskid.".bat","w");
            fwrite($bat,$cmd.PHP_EOL);
            fclose($bat);
			pclose(popen(PATH."FHL/runFastExe_ct".$taskid.".bat",'r'));
            //exec($cmd,$out);
            S('fhl_ctask')->update(['run'=>1],["taskid"=>$taskid]);
            if($taskid == 0)
			    $this->json(array('error'=>true,'info'=>'已启动高速远传进程:ct'.$taskid));
            else
                $this->json(array('error'=>true,'info'=>'已启动数据分发进程:ct'.$taskid));
		}elseif($type == 'r'){
			$task = S('fhl_ctask')->query('select * from hy_fhl_stask where taskid = '.$taskid)->fetchALL()[0];
            $this->existFHLexe("FastExe_st".$taskid.'.exe');
            $this->existFHLdir(C('FHLdirroot').$task['TD']);
            exec('taskkill /f /im FastExe_st'.$taskid.'.exe',$out);
			$cmd ='start /b '.PATH.'FHL/FastExe_st'.$taskid.'.exe -s '.$task['port'].' -TD '.C('FHLdirroot').$task['TD'].' -m '.$task['m'];
            $bat = fopen(PATH."FHL/runFastExe_st".$taskid.".bat","w");
            fwrite($bat,$cmd.PHP_EOL);
            fclose($bat);
            pclose(popen(PATH."FHL/runFastExe_st".$taskid.".bat",'r'));
            S('fhl_stask')->update(['run'=>1],["taskid"=>$taskid]);
			if($taskid == 0)
			    $this->json(array('error'=>true,'info'=>'已启高速远传接收进程:st'.$taskid));
			else
			    $this->json(array('error'=>true,'info'=>'已启数据汇聚进程:st'.$taskid));

		}elseif($type == 'p')
        {
            //代理加速
            $task = S('fhl_ptask')->query('select * from hy_fhl_ptask where taskid = '.$taskid)->fetchALL()[0];
            $pList = M("Sysinfo")->execCmd(' ps -elf |grep \'FHLproxy\'|awk \'{print $4 " " $15$16}\'');
            $pList = explode("\n",trim($pList));
            //关掉进程
            foreach($pList as $k=>$v){
                $v = explode(" ",$v);
                //$this->json("proxy".$task['type']);
                if(strpos($v[1],"FHL/FHLproxy")){
                    M("Sysinfo")->execCmd('kill -TERM '.$v[0]);
                }
            }
            $pList = M("Sysinfo")->execCmd(' ps -elf |grep \'FHLsocket5\'|awk \'{print $4 " " $15$16}\'');
            $pList = explode("\n",trim($pList));
            //关掉进程
            foreach($pList as $k=>$v){
                $v = explode(" ",$v);
                //$this->json("proxy".$task['type']);
                if(strpos($v[1],"FHL/FHLsocket5")){
                    M("Sysinfo")->execCmd('kill -TERM '.$v[0]);
                }
            }
            $rs=M("Sysinfo")->execCmd(INDEX_PATH."/FHL/FHLcontrol -lic");
            $rsArry = explode("\n",trim($rs,"\n"));
            //$this->json($rsArry);
            if(count($rsArry)>=3){
                $this->json([

                    "state"=>false,
                    "info"=>"授权错误，无法启动",
                    "con"=>$rs
                ]);
            }
            //启动进程 INDEX_PATH.
            if($task['type'] == "http"){
                $cmdtail = ' --daemon --forever --kcp-key mypassword --kcp-sndwnd='.$task['sndwnd'].' --kcp-rcvwnd='.$task['rcvwnd'].' --kcp-mtu='.$task['mtu'].' --kcp-method="none" --kcp-mode="fast3" --kcp-interval '.$task['interval'].' --http-header-timeout '.$task['hhtimeout'].' --http-header-buffer='.$task['hhbuf'].' --timeout '.$task['timeout'];
                if($task['level'] == 1){
                    //一级代理
                    M("Sysinfo")->execCmd(INDEX_PATH.'FHL/FHLproxy http -t kcp -m -p ":'.$task['lport'].'"'.$cmdtail);
                }elseif($task['level'] == 2){

                    M("Sysinfo")->execCmd(INDEX_PATH.'FHL/FHLproxy http -t tcp  -M -p ":'.$task['lport'].'" -T kcp -P "'.$task['rip'].':'.$task['rport'].'"'.$cmdtail);
                }

            }elseif ($task['type'] == "socket5"){
                $cmdtail = ' --daemon --forever --kcp-key mypassword --kcp-sndwnd='.$task['sndwnd'].' --kcp-rcvwnd='.$task['rcvwnd'].' --kcp-mtu='.$task['mtu'].' --kcp-method="none" --kcp-mode="fast3" --kcp-interval '.$task['interval'].' --timeout '.$task['timeout'];
                if($task['level'] == 1){
                    //一级代理
                    M("Sysinfo")->nohupExecCmd('sudo '.INDEX_PATH.'FHL/FHLproxy');
                    
                }elseif($task['level'] == 2){
                    //$fs = M("Sysinfo")->execCmd('sudo nohup '.INDEX_PATH.'FHL/FHLsocket5 '.$task['rip'].' &'); 
                     M("Sysinfo")->nohupExecCmd('sudo '.INDEX_PATH.'FHL/FHLsocket5 '.$task['rip']); 
                    //$fs = pclose(popen('nohup '.INDEX_PATH.'FHL/FHLsocket5 '.$task['rip'].' &', "w"));
                   
                    //M("Sysinfo")->nohupExecCmd(INDEX_PATH.'FHL/FHLsocket5 '.$task['rip']);
                }
            }

            S('fhl_ptask')->update(['run'=>1],["taskid"=>$taskid]);
            $this->json([
                "state"=>true,
                "info"=>"任务启动成功",
                //"con"=>$cmdtail
            ]);
        }elseif($type == 'g')
        {//网关加速重启
            $mode = trim(X('get.mode'));
            $lip = trim(X('get.lip'));
            $lport = trim(X('get.lport'));
            $rip = trim(X('get.rip'));
            $rport = trim(X('get.rport'));
            $destination = trim(X('get.destination'));
            $netmask = trim(X('get.netmask'));
            $localGate = trim(X('get.localGate'));
            $remoteGate = trim(X('get.remoteGate'));
            S('fhl_gtask')->update([
                'mode'=>$mode,
                'lip'=>$lip,
                'lport'=>$lport,
                'rip'=>$rip,
                'rport'=>$rport,
                'destination'=>$destination,
                'netmask'=>$netmask,
                'localGate'=>$localGate,
                'remoteGate'=>$remoteGate,
            ],[
                'gid'=>1
            ]);
            //$gtask = S('fhl_gtask')->query('select * from hy_fhl_gtask where gid = 1')->fetchALL()[0];
            $pList = M("Sysinfo")->execCmd(' ps -elf |grep \'FHLtun\'|awk \'{print $4 " " $15$16}\'');
            $pList = explode("\n",trim($pList));
            //关掉进程
            foreach($pList as $k=>$v){
                $v = explode(" ",$v);
                //$this->json("proxy".$task['type']);
                if(strpos($v[1],"FHLtun")){
                    $rs = M("Sysinfo")->execCmd('/home/www/kill -TERM '.$v[0]);
                }
            }
            //删除直通路由
            M("Sysinfo")->execCmd('sudo /usr/sbin/route del -net '.$destination.' netmask '.$netmask.' gw '.$rip);
            $rs=M("Sysinfo")->execCmd(INDEX_PATH."/FHL/FHLcontrol -lic");
            $rsArry = explode("\n",trim($rs,"\n"));
            //$this->json($rsArry);
            if(count($rsArry)>=3){
                $this->json([
                    "state"=>false,
                    "info"=>"授权错误，无法启动，请返回【设置页面】查看",
                    "con"=>$rs
                ]);
            }
            if($mode=='c'){
                //客户端
                M("Sysinfo")->nohupExecCmd('sudo '.INDEX_PATH.'FHL/FHLtun -c -i '.$lip.' -r '.$rip.' -p '.$rport.' -d '.$destination.' -m '.$netmask.' ');
            }else{
                M("Sysinfo")->nohupExecCmd('sudo '.INDEX_PATH.'FHL/FHLtun -s -i '.$lip.' -p '.$lport.' -d '.$destination.' -m '.$netmask.' ');
            }
                $this->json([
                    "state"=>true,
                    "info"=>"已启动",
                ]);
        }elseif($type == 'tcp_g')
        {//TCP网关加速重启
          
           
            //$gtask = S('fhl_gtask')->query('select * from hy_fhl_gtask where gid = 1')->fetchALL()[0];
            $pList = M("Sysinfo")->execCmd(' ps -elf |grep \'FTCPG\'|grep -v \' www \'|grep \'sudo\'|awk \'{print $4 " " $15$16}\'');
            $pList = explode("\n",trim($pList));
            //关掉进程
            foreach($pList as $k=>$v){
                            $v = explode(" ",$v);
                            //$this->json("proxy".$task['type']);
                            if(count($v)>1 && strpos($v[1],"FTCPG")){
                                $rs = M("Sysinfo")->execCmd('/home/www/kill -TERM '.$v[0]);
                            }
                        }
            
            
            //删除直通路由
            //M("Sysinfo")->execCmd('sudo /usr/sbin/route del -net '.$destination.' netmask '.$netmask.' gw '.$rip);
            $rs=M("Sysinfo")->execCmd(INDEX_PATH."/FHL/FHLcontrol -lic");
            $rsArry = explode("\n",trim($rs,"\n"));
            //$this->json($rsArry);
            if(count($rsArry)>=3){
                $this->json([
                    "state"=>false,
                    "info"=>"授权错误，无法启动，请返回【设置页面】查看",
                    "con"=>$rs
                ]);
            }
           //全部启动
           M("Sysinfo")->execCmd('sudo '.INDEX_PATH.'FHL/iptables.sh ');
           for ($i=0; $i<=10; $i++)
           {
               //0是服务端 用于接收任务
               if($i == 0){
                   M("Sysinfo")->execCmdClose('cd '.INDEX_PATH.'FHL/tcpGateWay/'.$i.' && nohup sudo '.INDEX_PATH.'FHL/tcpGateWay/'.$i.'/FTCPG_Remote'.' &');
                   
               }else{
                   $iniArray =parse_ini_file(INDEX_PATH . 'FHL/tcpGateWay/'.$i.'/local.ini');
                   M("Sysinfo")->execCmdClose('cd '.INDEX_PATH.'FHL/tcpGateWay/'.$i.' && nohup sudo '.INDEX_PATH.'FHL/tcpGateWay/'.$i.'/FTCPG_Local'.$i.' &');
                   //echo 'cd '.INDEX_PATH.'FHL/tcpGateWay/'.$i.' && nohup sudo '.INDEX_PATH.'FHL/tcpGateWay/'.$i.'/FTCPG_Local'.$i.' &';
                   M("Sysinfo")->execCmd("/usr/sbin/iptables -t mangle -A PREROUTING -p tcp -d ".$iniArray['speednet']." -j TPROXY --on-port ".$iniArray['listenport']." --tproxy-mark 1");
               }
               
           }
           
                $this->json([
                    "state"=>true,
                    "info"=>"已启动",
                ]);


        }
	}

	public function killTask(){
		$type = X('get.type');
		$taskid = intval(X('get.taskid'));
		if($type == 't'){
			exec('taskkill /f /im FastExe_ct'.$taskid.'.exe');
            S('fhl_ctask')->update(['run'=>0],["taskid"=>$taskid]);
            S('fhl_ctask')->query("INSERT INTO eventlog (content, cdt) VALUES ('killtask-t".$taskid."', '".date("Y-m-d H:i:s")."')");
            $this->json(array('error'=>true,'info'=>'已关闭发送进程_ct'.$taskid));
		}elseif($type == 'r'){
			exec('taskkill /f /im FastExe_st'.$taskid.'.exe');
            S('fhl_stask')->update(['run'=>0],["taskid"=>$taskid]);
            S('fhl_ctask')->query("INSERT INTO eventlog (content, cdt) VALUES ('deletetask-r".$taskid."', '".date("Y-m-d H:i:s")."')");
			$this->json(array('error'=>true,'info'=>'已关闭接收进程_st'.$taskid));
		}
        elseif($type == 'p'){
            $task = S('fhl_ptask')->query('select * from hy_fhl_ptask where taskid = '.$taskid)->fetchALL()[0];
            $pList = M("Sysinfo")->execCmd(' ps -elf |grep \'FHLproxy\'|awk \'{print $4 " " $15$16}\'');
            $pList = explode("\n",trim($pList));
            //关掉进程
            foreach($pList as $k=>$v){
                $v = explode(" ",$v);
                //$this->json("proxy".$task['type']);
                if(strpos($v[1],"FHL/FHLproxy")){
                    M("Sysinfo")->execCmd('sudo kill -TERM '.$v[0]);
                }
            }
            $pList = M("Sysinfo")->execCmd(' ps -elf |grep \'FHLsocket5\'|awk \'{print $4 " " $15$16}\'');
            $pList = explode("\n",trim($pList));
            //关掉进程
            foreach($pList as $k=>$v){
                $v = explode(" ",$v);
                //$this->json("proxy".$task['type']);
                if(strpos($v[1],"FHL/FHLsocket5")){
                    M("Sysinfo")->execCmd('sudo kill -TERM '.$v[0]);
                }
            }
            S('fhl_ptask')->update(['run'=>0],["taskid"=>$taskid]);
            S('fhl_ctask')->query("INSERT INTO eventlog (content, cdt) VALUES ('kill proxy task -".$task['type'].$taskid."', '".date("Y-m-d H:i:s")."')");
            $this->json(array('state'=>true,'info'=>'已关闭'.$task['type'].$taskid));
        }
        elseif($type == 'g'){
            $pList = M("Sysinfo")->execCmd(' ps -elf |grep \'FHLtun\'|awk \'{print $4 " " $15$16}\'');
            $pList = explode("\n",trim($pList));
            //关掉进程
            foreach($pList as $k=>$v){
                $v = explode(" ",$v);
                //$this->json("proxy".$task['type']);
                if(strpos($v[1],"FHLtun")){
                    $rs = M("Sysinfo")->execCmd('/home/www/kill -TERM '.$v[0]);
                }
            }
            $this->json([
                'state'=>true,
                'info'=>'已关闭'
            ]);
        }elseif($type == 'tcp_g'){
            $pList = M("Sysinfo")->execCmd(' ps -elf |grep \'FTCPG\'|awk \'{print $4 " " $15$16}\'');
            $pList = explode("\n",trim($pList));
            //关掉进程
            foreach($pList as $k=>$v){
                $v = explode(" ",$v);
                //$this->json("proxy".$task['type']);
                if(strpos($v[1],"FTCPG")){
                    $rs = M("Sysinfo")->execCmd('/home/www/kill -TERM '.$v[0]);
                   
                }
            }
            $rs = M("Sysinfo")->execCmd('sudo iptables -t mangle -F ');
            $this->json([
                'state'=>true,
                'info'=>'已关闭'
            ]);
        }
	}
	//清理任务 包括进程和收发文件夹
	public function deleteTask(){
        $type = X('get.type');
        $taskid = intval(X('get.taskid'));
        $delexe = false;
        $deldir = false;
        if($type == 't'){
            $task = S('fhl_ctask')->query('select * from hy_fhl_ctask where taskid = '.$taskid)->fetchALL()[0];
            exec('taskkill /f /im FastExe_ct'.$taskid.'.exe');
            S('fhl_ctask')->update(['run'=>0],["taskid"=>$taskid]);
            $delexe = $this->delfile(PATH.'FHL/FastExe_ct'.$taskid.'.exe');
            $deldir = $this->deldir(C('FHLdirroot').$task['SD']);
            S('fhl_ctask')->query("INSERT INTO eventlog (content, cdt) VALUES ('deletetask-t".$taskid."', '".date("Y-m-d H:i:s")."')");

        }elseif($type == 'r'){
            exec('taskkill /f /im FastExe_st'.$taskid.'.exe');
            $task = S('fhl_stask')->query('select * from hy_fhl_stask where taskid = '.$taskid)->fetchALL()[0];
            S('fhl_stask')->update(['run'=>0],["taskid"=>$taskid]);
            $delexe = $this->delfile(PATH.'FHL/FastExe_st'.$taskid.'.exe');
            $deldir = $this->deldir(C('FHLdirroot').$task['TD']);
            S('fhl_ctask')->query("INSERT INTO eventlog (content, cdt) VALUES ('deletetask-r".$taskid."', '".date("Y-m-d H:i:s")."')");
        }
        if($delexe&&$deldir){
            $this->json(array('error'=>true,'info'=>'已清空任务'.$taskid));
        }else{
            $this->json(array('error'=>false,'info'=>'没有需要清空的内容'.$taskid));
        }
    }

    public function getTaskLog(){
        $type = X('get.type');
        $taskid = intval(X('get.taskid'));
        $start = "";
        $end = "";
        $data = [];
        if($type == "t"){
            $data = S('fhl_ctask')->query("select l.* from (SELECT * FROM clientlog  ORDER BY lid desc limit 1000) l
                                         join hy_fhl_ctask t on t.taskid = ".$taskid." and l.rootDir LIKE '%'||t.SD order by l.lid ")->fetchALL();
        }else{
            $data = S('fhl_ctask')->query("select l.* from (SELECT * FROM serverlog ORDER BY lid desc limit 1000) l
                                         join hy_fhl_stask t on t.taskid = ".$taskid." and l.rootDir LIKE '%'||t.TD order by l.lid")->fetchALL();
        }
        $this->json([
            "error"=>true,
            "data"=>$data,
            "count"=>count($data)
        ]);

    }
    //直通路由
    public function directRoute(){
        $destination = trim(X('get.destination'));
        $netmask = trim(X('get.netmask'));
        $gw = trim(X('get.rip'));
        $pList = M("Sysinfo")->execCmd(' ps -elf |grep \'FHLtun\'|awk \'{print $4 " " $15$16}\'');
        $pList = explode("\n",trim($pList));
        //关掉进程
        foreach($pList as $k=>$v){
            $v = explode(" ",$v);
            //$this->json("proxy".$task['type']);
            if(strpos($v[1],"FHLtun")){
                $rs = M("Sysinfo")->execCmd('/home/www/kill -TERM '.$v[0]);
            }
        }
        M("Sysinfo")->execCmd('sudo /usr/sbin/route add -net '.$destination.' netmask '.$netmask.' gw '.$gw);

        $this->json([
            'state'=>true,
            'info'=>'已添加直通路由'
        ]);

    }
    //将FHL路径下的执行文件复制成指定名字
    protected function existFHLexe($exename){
        if(!file_exists(PATH.'FHL/'.$exename)){
           // '文件不存在！';
            copy(PATH.'FHL/FastExe.exe', PATH.'FHL/'.$exename);
        }
    }
    //
    protected function existFHLdir($dir){

        if(!file_exists($dir)){
            // '文件不存在！就创建';
            $this->existFHLdir(dirname($dir));
            mkdir($dir);

        }
    }
    protected function delfile($file){
        if(file_exists($file)){
            return unlink($file);
        }else{
            return true;
        }
    }
    //删除非空目录
    protected function deldir($dir) {
        if(!is_dir($dir))
            return false;
        $dh=opendir($dir);
        while ($file=readdir($dh)) {
            if($file!="." && $file!="..") {
                $fullpath=$dir."/".$file;
                if(!is_dir($fullpath)) {
                    unlink($fullpath);
                } else {
                    $this->deldir($fullpath);
                }
            }
        }
        closedir($dh);
        if(rmdir($dir)) {
            return true;
        } else {
            return false;
        }
    }
    public function pauth(){
        $proxy_ip=$_GET['local_addr'];
        $user_ip=$_GET['client_addr'];
        $service=$_GET['service'];
        $is_sps=$_GET['sps']=='1';
        $user=$_GET['user'];
        $pass=$_GET['pass'];
        $target=$_GET['target'];
        $task = S('fhl_ptask')->query('select * from hy_fhl_ptask where type = '.$service)->fetchALL()[0];
        //header("userconns:1000");
        //header("ipconns:2000");
        //header("userrate:3000");
        header("iprate:".$task['ipspeed']*1000*1000);
       // header("userqps:5");
        //header("ipqps:2");
        //header("upstream:http://127.0.0.1:3500?parent-type=tcp");
        //header("outgoing:1.1.1.1");
        //header("userTotalRate:1024000");
        //header("ipTotalRate:10240");
        //header("portTotalRate:10240");
        header("HTTP/1.1 204 No Content");
    }


}
